package com.chenshuang.web;

import com.chenshuang.bean.Admin;
import com.chenshuang.service.AdminServise;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;

@WebServlet(name = "RegisterServlet", value = "/Register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //更改编码格式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //从浏览器获取数据
        Map<String, String[]> map = request.getParameterMap();
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 获取到的数据打印到控制台
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            System.out.println(entry.getKey()+":"+Arrays.toString(entry.getValue()));
        }

        AdminServise adminServise = new AdminServise();

        Boolean istrue =  adminServise.insert(admin);

        if (istrue){
            System.out.println("注册成功");
            request.getRequestDispatcher("registerSuccess.jsp").forward(request,response);
        }else{
            System.out.println("失败！！！");
            request.setAttribute("r1","用户名重复啦");
            request.setAttribute("r2","请重新注册哦~");
            request.getRequestDispatcher("reregister.jsp").forward(request,response);
        }

    }
}
